var ZOO = window.ZOO || {};
var player;
var ready;

//inject the JS
/*var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);*/

ZOO.VideoPlayer = function(e, videoId){
  var pub = {
    elem: e,
    player: null,
    index:0,
    videoList:null,
    initVideoId:videoId,
    ready: false,

    init: function(){
      
      this.player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: this.initVideoId,
        events: {
          'onReady': $.proxy(this.onPlayerReady, this),
          'onStateChange': $.proxy(this.onPlayerStateChange, this)
        },
        playerVars:{
          
        }

      });
    },
    setVideoList: function(videoList){
      this.videoList = videoList;
    },
    playVideoList: function(){
      this.player.loadVideoById(this.videoList[this.index]);
    },
    playVideoByIndex: function(index){
      this.index = index;
      this.playVideoList();
    },
    playVideoById: function(id){
      this.player.loadVideoById(id);
    },
    playVideo: function(){
      this.player.playVideo();
    },
    pauseVideo: function(){
      this.player.pauseVideo();
    },
    seekToAndPlay: function(secs){
      this.player.seekTo(secs);
      this.player.playVideo();
    },
    getCurrentTime: function(){
      return this.player.getCurrentTime();
    },
    nextVideo: function(){
      if(this.index + 1 >= this.videoList.length){
        $(this).trigger('endOfList');
        return false;
      }
      this.index++;
      this.playVideoList();
      $(this).trigger('next');

      return true;
    },
    onPlayerReady: function(event){
      //event.target.playVideo();
      //console.log(this);
      $(this).trigger('ready');
      this.ready = true;
      
    }, 
    onPlayerStateChange: function(event){
      //console.log(event.data);
      if (event.data == YT.PlayerState.PLAYING) {
        console.log('playing');
      }else if(event.data === YT.PlayerState.ENDED){
        $(this).trigger('ended');
      }
      
    },
    stopVideo: function(){
      this.player.stopVideo();
    },


  }
  return pub;
};




